<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.user_attendance_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="打卡日期" prop="checkDate">
        <el-date-picker clearable
                        v-model="queryParams.checkDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择打卡日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:attendance:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:attendance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考勤ID" align="center" prop="id" />
      <el-table-column label="上午打卡时间" align="center" prop="morning" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.morning }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下午打卡时间" align="center" prop="afternoon" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.afternoon }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_attendance_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <el-table-column label="打卡日期" align="center" prop="checkDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:attendance:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考勤对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttendance, getAttendance, delAttendance, addAttendance, updateAttendance } from "@/api/system/attendance"

export default {
  name: "Attendance",
  dicts: ['user_attendance_status'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      attendanceList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        userId: null, // 用于筛选当前用户的考勤
        checkDate: null
      },
      form: {},
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询考勤列表（核心修复：精准获取角色和用户ID） */
    getList() {
      this.loading = true
      const params = { ...this.queryParams }

      // 1. 从getters获取当前用户的角色和ID（严格按照若依的getters配置）
      const userRoles = this.$store.getters.roles  // 角色列表（如 ['admin'] 或 ['common']）
      const currentUserId = this.$store.getters.id // 当前用户ID（对应getters中的id字段）

      // 2. 调试输出（方便排查问题，可保留）
      console.log("当前用户角色：", userRoles)
      console.log("当前用户ID：", currentUserId)

      // 3. 角色判断逻辑：
      // - 管理员(admin)：查询所有数据（不设置userId）
      // - 普通用户(common)：仅查询自己的考勤（强制设置userId为当前用户ID）
      if (userRoles && userRoles.length > 0) {
        const isAdmin = userRoles.includes('admin')
        const isCommonUser = userRoles.includes('common')

        if (!isAdmin && isCommonUser && currentUserId) {
          params.userId = currentUserId // 普通用户强制筛选自身数据
          console.log("普通用户，筛选条件userId：", params.userId)
        } else {
          console.log("管理员，查询所有数据")
        }
      } else {
        console.warn("未获取到用户角色，默认查询所有数据")
      }

      // 4. 调用接口查询
      listAttendance(params).then(response => {
        this.attendanceList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error("查询考勤失败：", error)
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        morning: null,
        afternoon: null,
        status: null,
        userId: null,
        checkDate: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加考勤"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row?.id || this.ids
      getAttendance(id).then(response => {
        this.form = response.data || {}
        this.open = true
        this.title = "修改考勤"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAttendance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAttendance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row?.id || this.ids
      this.$modal.confirm('是否确认删除考勤编号为"' + ids + '"的数据项？').then(function() {
        return delAttendance(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作（同步权限过滤） */
    handleExport() {
      const params = { ...this.queryParams }
      const userRoles = this.$store.getters.roles
      const currentUserId = this.$store.getters.id

      if (userRoles && userRoles.includes('common') && !userRoles.includes('admin') && currentUserId) {
        params.userId = currentUserId
      }
      this.download('system/attendance/export', params, `attendance_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
